package com.barunlab.ems.library;


import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * 메시지를 큐잉하여 비동기로 처리하는 클래스
 * 
 * @author 배수현
 * @version R1.0
 * @since JDK6.0
 * @created 2013
 */
public abstract class QueueWorker<T> extends Thread {
    private LinkedList<T> eventLinkedList = new LinkedList<T>();
    private List<T> messageQueue = Collections.synchronizedList(eventLinkedList);

    private Object waitObject = new Object();
    
    private boolean runFlag;

    public abstract void processObject(T t);

    public void push(T t) {
        messageQueue.add(t);

        synchronized ( waitObject ) {
            waitObject.notify();
        }
    }

    public void run() {
        T t = null;
        runFlag = true;

        while ( runFlag ) {
            synchronized ( waitObject ) {
                if ( messageQueue.size() > 0 ) {
                    t = messageQueue.remove(0);
                }
                else {
                    t = null;

                    try {
                        waitObject.wait();
                    }
                    catch ( Exception ex ) {
                        ex.printStackTrace();
                    }
                }
            }

            try {
                if ( t != null ) {
                    processObject(t);
                }
            }
            catch ( Exception ex ) {
                ex.printStackTrace();
            }
        }
    }
    
    public void close() {
    	runFlag = false;
    	
    	synchronized ( waitObject ) {
    		waitObject.notify();
    	}
    }
	
	public int getQueueSize()
	{
		return messageQueue.size();
	}
}
